--Dictionary
--[[
    HTDictionary：自定义 Dictionary 容器（使用一个列表维护 key，一个 table 维护 value）
    API:
        New
        Count
        KeyType
        ValueType
        TryGetValue
        Add
        ContainsKey
        ContainsValue
        Remove
        Clear
        GetIterator
--]]

Dictionary = {}
Dictionary.__index = Dictionary

Dictionary.New = function(self,keyType,valueType)
    m = {}
    m.keyType = keyType
    m.valueType = valueType
    setmetatable(m,Dictionary)
    self.keyList = {}
    return m
end
--获取键值对对数
Dictionary.Count = function(self)
    return table.getn(self.keyList)
end
--获取 key 类型
Dictionary.KeyType = function(self)
    return self.keyType
end
--获取 value 类型
Dictionary.ValueType = function(self)
    return self.valueType
end
--通过 key 尝试获取 value
Dictionary.TryGetValue = function(self,key)
    if self:ContainsKey(key) then
        return true,self[key]
    else
        return false,nil
    end
end
--添加键值对
Dictionary.Add = function(self,key,value)
    if self[key] then
        self[key] = value
    else
        table.insert(self.keyList,key)
        self[key] = value
    end
end
--判断是否包含指定 key 值
Dictionary.ContainsKey = function(self,key)
    local count = self:Count()
    for i = 1,count do
        if self.keyList[i] == key then
            return true
        end
    end
    return false
end
--判断是否包含指定 value 值
Dictionary.ContainsValue = function(self,value)
    local count = self:Count()
    for i = 1,count do
        if self[self.keyList[i]] == value then
            return true
        end
    end
    return false
end
--移除指定 key 值的键值对
Dictionary.Remove = function(self,key)
    if not self:ContainsKey(key) then return false end
    local count = self:Count()
    for i = count,1,-1 do
        if self.keyList[i] == key then
            table.remove(self.keyList,i)
        end
    end
    self[key] = nil
    return true
end
--清空字典
Dictionary.Clear = function(self)
    local count = self:Count()
    for i = count,1,-1 do
        self[self.keyList[i]] = nil
        table.remove(self.keyList,i)
    end
end
--获取迭代器（内用闭包，供键值对遍历）
Dictionary.GetIterator = function(self)
    local i = 0
    local count = self:Count()
    return function()
        i = i + 1
        if i <= count then
            return self.keyList[i],self[self.keyList[i]]
        else
            return nil,nil
        end
    end
end

return Dictionary